<script setup>
import AMap from '@/components/AMap/AMap.vue';
import api from '@/api/index.js'
import { ref } from 'vue'
import { getConsants } from '@/utils'

const show = ref(false)
const title = ref('地图预览')
const open = () => {
  show.value = true
}

// 绘制区域
const drawArea = item => {
  const defaultPStyle = {
    strokeColor: ['#deff00', '#68ff00', '#ff4d00'][item.status],
    strokeWeight: 2,
    strokeOpacity: 0.9,
    fillColor: ['#deff00', '#68ff00', '#ff4d00'][item.status],
    fillOpacity: 0.2,
    // 线样式还支持 'dashed'
    strokeStyle: "solid",
    // strokeStyle是dashed时有效
    // strokeDasharray: [30,10],
  }
  if (item?.positionList?.length > 0) {
    const polygon = new curAMap.Polygon({
      map: curMap,
      path: item.positionList.map(ele => [ele.lng, ele.lat]),
      ...defaultPStyle,
      zIndex: 300
    });
    polygon.on('click', event => openWindow({ event, item }))
  }

  curMap.setFitView()
}
// 获取区域经纬度数据
const getAreaData = async () => {
  const { resultObject } = await api.getAllMassif()
  resultObject.map(drawArea)
}

// 地图加载完成回调函数
let curAMap = null
let curMap = null
const mapInit = (AMap, map) => {
  curAMap = AMap
  curMap = map
  getAreaData()
}
// 获取点位中心点
function getCenter (coordinates) {
  let sumLat = 0;
  let sumLon = 0;
  let count = coordinates.length;

  for (let i = 0; i < coordinates.length; i++) {
    sumLat += coordinates[i].lat;
    sumLon += coordinates[i].lng;
  }

  return {
    lat: sumLat / count,
    lng: sumLon / count
  };
}
const openWindow = ({ event, item }) => {
  const path = event.target.getPath()
  const center = getCenter(path)
  var info = [];
  info.push(`<p class='input-item'>地块名称：${item.landName}`);
  info.push(`<p class='input-item'>地块地址：${item.landAddress}`);
  info.push(`<p class='input-item'>地块性质：${getConsants('land_nature', item.landNature)}`);
  info.push(`<p class='input-item'>地块面积：${item.landArea} 亩`);
  info.push(`<p class='input-item'>地块属性：${getConsants('land_attribute', item.landAttribute)}`);
  info.push(`<p class='input-item'>种植作物类型：${getConsants('plant_type', item.plantType)}`);
  info.push(`<p class='input-item'>所属合作社：${item.deptName}`);
  info.push(`<p class='input-item'>备注：${item.remark ?? '--'}`);

  const infoWindow = new curAMap.InfoWindow({
    content: info.join("")  //使用默认信息窗体框样式，显示信息内容
  });
  infoWindow.open(curMap, new curAMap.LngLat(center.lng, center.lat));
}

defineExpose({ open })
</script>

<template>
  <a-modal v-model:open="show" :title="title" style="width: 1200px;" destroyOnClose>
    <div style="height: 800px;">
      <AMap :mapInit="mapInit" />
    </div>
    <template #footer>
      <a-button @click="show = false">关闭</a-button>
    </template>
  </a-modal>
</template>